package com.freesky.biz.icbc.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.freesky.biz.icbc.config.IcbcConfiguration;
import com.freesky.biz.icbc.model.WjyxCustmIdentifyRequestV1;
import com.freesky.biz.icbc.model.WjyxCustmIdentifyResponseV1;
import com.freesky.biz.icbc.model.WjyxEquityRequestV1;
import com.freesky.biz.icbc.model.WjyxEquityResponseV1;
import com.freesky.common.core.domain.AjaxResult;
import com.icbc.api.DefaultIcbcClient;
import com.icbc.api.IcbcConstants;
import com.icbc.api.UiIcbcClient;
import com.icbc.api.request.*;
import com.icbc.api.response.*;
import com.icbc.api.utils.IcbcEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class IcbcLifeService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("icbcConfiguration")
    private IcbcConfiguration icbcConfiguration;

    private String PREFIX_URL = "https://gw.open.icbc.com.cn/api/";
    private String PREFIX_UI = "https://gw.open.icbc.com.cn/ui/";

    //测试环境
    //private String PREFIX_URL = "https://apipcs3.dccnet.com.cn/api/";

    //E生活参数解密
    public String decryptContent(String encryptContent){
        String result = "";
        try {
            String decodeLoginParams = URLDecoder.decode(encryptContent, "UTF-8");
            decodeLoginParams = decodeLoginParams.replace(" ", "+");

            String base64Org = IcbcEncrypt.decryptContent(decodeLoginParams, "AES",
                    icbcConfiguration.getAesEncryptKey(), "UTF-8");

            result = new String(Base64.decodeBase64(base64Org));

        } catch (Exception ioe){
            ioe.printStackTrace();
        }
        return result;
    }

    //福建分行客户权益查询（个金）
    public AjaxResult wjyxEquityQry(String userId, String activityId,
                                    String activityDate, String month,
                                    String mobileNo){
        try{
            DefaultIcbcClient client = new DefaultIcbcClient(icbcConfiguration.getAppId(),
                    IcbcConstants.SIGN_TYPE_RSA2,
                    icbcConfiguration.getPrivateKey(),
                    icbcConfiguration.getPubGatewayKey());

            WjyxEquityRequestV1 request = new WjyxEquityRequestV1();
            request.setServiceUrl(PREFIX_URL + "fjfh/mybank/account/wjyx/equityqry/V1");
            WjyxEquityRequestV1.WjyxEquityRequestV1Biz bizContent = new WjyxEquityRequestV1.WjyxEquityRequestV1Biz();

            bizContent.setUserId(userId);
            if(StringUtils.isNotEmpty(activityId)){
                bizContent.setActivityid(activityId);
            }
            if(StringUtils.isNotEmpty(activityDate)){
                bizContent.setActivitydate(activityDate);
            }
            if(StringUtils.isNotEmpty(month)){
                bizContent.setMonth(month);
            }
            bizContent.setMobileno(mobileNo);
            bizContent.setTranTime(DateUtil.format(new Date(),"yyyyMMddHHmmss"));
            request.setBizContent(bizContent);

            logger.info("【wjyxEquityQry req】:"+JSON.toJSONString(bizContent));
            WjyxEquityResponseV1 response = client.execute(request);
            logger.info("【wjyxEquityQry resp】:"+JSON.toJSONString(response));
            if (response.isSuccess()) {
                Map<String,String> respMap = new HashMap<>();
                respMap.put("retcode",response.getRetcode());
                respMap.put("userId",response.getUserId());
                respMap.put("activityId",response.getActivityId());
                respMap.put("xkflag",response.getXkflag());
                respMap.put("zfflag",response.getZfflag());
                respMap.put("dfflag",response.getDfflag());
                respMap.put("sbflag",response.getSbflag());
                respMap.put("ylflag",response.getYlflag());
                respMap.put("msflag",response.getMsflag());
                respMap.put("echange",response.getEchange());
                respMap.put("openTime",response.getOpenTime());
                return AjaxResult.success(respMap);
            } else {
                return AjaxResult.error(response.getReturnMsg());
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            return AjaxResult.error(ioe.getMessage());
        }
    }

    //旺季营销项目客户身份认证(个金)
    public AjaxResult wjyxCustmIdentifyQry(String mobileNo,String idno){
        try{
            DefaultIcbcClient client = new DefaultIcbcClient(icbcConfiguration.getAppId(),
                    IcbcConstants.SIGN_TYPE_RSA2,
                    icbcConfiguration.getPrivateKey(),
                    icbcConfiguration.getPubGatewayKey());

            WjyxCustmIdentifyRequestV1 request = new WjyxCustmIdentifyRequestV1();
            request.setServiceUrl(PREFIX_URL + "fjfh/mybank/account/wjyx/custmidentify/V1");
            WjyxCustmIdentifyRequestV1.WjyxCustmIdentifyRequestV1Biz bizContent = new WjyxCustmIdentifyRequestV1.WjyxCustmIdentifyRequestV1Biz();

            bizContent.setMobileno(mobileNo);
            if(StringUtils.isNotEmpty(idno)){
                bizContent.setIdno(idno);
            } else {
                bizContent.setIdno("");
            }
            bizContent.setTranTime(DateUtil.format(new Date(),"yyyyMMddHHmmss"));
            request.setBizContent(bizContent);

            logger.info("【wjyxCustmIdentifyQry req】:"+request.getServiceUrl()+","+ JSON.toJSONString(bizContent));
            WjyxCustmIdentifyResponseV1 response = client.execute(request);
            logger.info("【wjyxCustmIdentifyQry resp】:"+JSON.toJSONString(response));
            if (response.isSuccess()) {
                Map<String,String> respMap = new HashMap<>();
                respMap.put("retcode",response.getRetcode());
                respMap.put("retmsg",response.getRetmsg());
                respMap.put("userId",response.getUserId());
                respMap.put("mobileNo",response.getMobileNo());
                return AjaxResult.success(respMap);
            } else {
                return AjaxResult.error(response.getReturnMsg());
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            return AjaxResult.error(ioe.getMessage());
        }
    }


    public AjaxResult customDsfApiService(String customId,
                                          String mobile,
                                          String customerType){
        try{
            DefaultIcbcClient client = new DefaultIcbcClient(icbcConfiguration.getAppId(),
                    IcbcConstants.SIGN_TYPE_RSA2,
                    icbcConfiguration.getPrivateKey(),
                    icbcConfiguration.getPubGatewayKey());

            CustomerCustomDsfApiServiceRequestV2 request = new CustomerCustomDsfApiServiceRequestV2();
            request.setServiceUrl(PREFIX_URL + "customer/customDsfApiService/V2");
            CustomerCustomDsfApiServiceRequestV2.CustomerCustomDsfApiServiceRequestV2Biz bizContent = new CustomerCustomDsfApiServiceRequestV2.CustomerCustomDsfApiServiceRequestV2Biz();
            bizContent.setCustomId(customId);
            bizContent.setPhone(mobile);
            bizContent.setCustomType(customerType);
            request.setBizContent(bizContent);

            CustomerCustomDsfApiServiceResponseV2 responseV2 = new CustomerCustomDsfApiServiceResponseV2();

            logger.info("customDsfApiService req【mobile:"+mobile+"】"+ com.alibaba.fastjson2.JSON.toJSONString(request));
            CustomerCustomDsfApiServiceResponseV2 response = client.execute(request);
            logger.info("customDsfApiService Resp【mobile:"+mobile+"】"+ com.alibaba.fastjson2.JSON.toJSONString(response));
            if (response.isSuccess()) {
                AjaxResult ajaxResult = AjaxResult.success();
                if("0".equalsIgnoreCase(response.getRet_code())){
                    //0-证明在客群中 1-不在客群中，res = 0 时返回，否则为空
                    ajaxResult.put(AjaxResult.DATA_TAG,response.getRet_code());
                } else {
                    //失败
                    ajaxResult.put(AjaxResult.DATA_TAG,"-1");
                }
                return ajaxResult;
            } else {
                return AjaxResult.error(response.getReturnMsg());
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常");
        }
    }
}
